﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Loong.Dependency;
using Loong.Domain.Entities;

namespace Loong.Dapper.Filters.Query
{
    public class DapperQueryFilterExecuter : IDapperQueryFilterExecuter, ITransientDependency
    {
        private readonly IEnumerable<IDapperQueryFilter> _queryFilters;

        public DapperQueryFilterExecuter(IEnumerable<IDapperQueryFilter> queryFilters)
        {
            _queryFilters = queryFilters;
        }

        public Expression<Func<TEntity, bool>> ExecuteFilter<TEntity, TPrimaryKey>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, IEntity<TPrimaryKey>
        {
            ICollection<IDapperQueryFilter> filters = _queryFilters.ToList();

            foreach (IDapperQueryFilter filter in filters)
            {
                predicate = filter.ExecuteFilter<TEntity, TPrimaryKey>(predicate);
            }

            return predicate;
        }
    }
}
